#include "thread_pool.hpp"
#include "worker_thread.hpp"
#include "thread_task.hpp"
#include <thread>
#include <chrono>

#include <glog/logging.h>
thread_pool::thread_pool(/* args */)
{
}

thread_pool::~thread_pool()
{
}
thread_pool* thread_pool::getInstance()
{
    static thread_pool t;
    return &t;
}
void thread_pool::init(int thread_count)
{
    this->m_count = thread_count;
    for (unsigned int i = 0; i < thread_count; i++)
    {
        worker_thread *t = new worker_thread();
        t->start();
        t->set_pthread_id(i+1);
        m_threads.push_back(t);
        std::this_thread::sleep_for(std::chrono::microseconds(10));
    }
}
void thread_pool::dispatch(thread_task* task)
{
    // 取余轮询法分发线程
    if(!task) return;
    int tid = (m_last_thread+1)%this->m_count;
    m_last_thread = tid;
    worker_thread* work = m_threads[tid]; 
    VLOG(0)<<"signal threads"<<tid;
    work->add_task(task); // 把任务添加到任务链中
    work->activate(); // 激发线程
    
}